import {Breadcrumb, Button, Card, Input, Select, Form, Radio, Upload, message} from 'antd'
import {
    FormOutlined,
    HomeOutlined,
    PlusOutlined,
    PlusSquareOutlined,
} from "@ant-design/icons";
import "./index.scss"

import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import {getArticleDetailAPI, PublishAPI} from '@/apis'
import React, {useEffect, useState} from "react";
import useChannels from "@/hooks/useChannels";
import {Link, useSearchParams} from "react-router-dom";
import {updateArticleAPI} from "@/apis/ArticleApi";

const Publish = () => {
    // 获取频道列表数据
    const {channelList} = useChannels()
    // 解构option属性
    const {Option} = Select
    // 收集表单数据
    const FormRef = React.createRef()
    const onFinish = (form) => {
        // 校验 封面类型是否与上传图片数量匹配
        if (downLoad.length !== onType) return message.warning("封面类型与图片数量不匹配")
        // 发布文章
        // 1. 按照接口文档的格式，整理数据
        const {title, content, channel_id} = form
        // 筛选我们需要的url数据 这里不能用filter方法，filter方法会把整个item筛选出来
        const imgList = downLoad.map(item => {
            if (item.response) {
                return item.response.data.url
            } else {
                return item.url
            }
        })
        const PublishData = {
            title,
            content,
            cover: {
                type: onType, // 封面类型
                images: imgList // 图片列表
            },
            channel_id
        }
        // 2. 调用接口 传递表单数据
        if (articleId) {
            updateArticleAPI({...PublishData, id: articleId})
            message.success("修改文章成功")
        } else {
            PublishAPI(PublishData)
            message.success("发布文章成功")
        }
        setOnType(0)
        setDownLoad([])
        FormRef.current.resetFields()

    };

    // 上传图片 回调
    // 拿到上传图片的文件列表
    const [downLoad, setDownLoad] = useState([])
    const onUploadChange = (value) => {
        setDownLoad(value.fileList)
    }

    // 切换封面图片类型
    const [onType, setOnType] = useState(0)
    const onTypeChange = (val) => {
        setOnType(val.target.value)
    }


    // 文章详情 - 回填数据
    const [SearchParams] = useSearchParams()
    const articleId = SearchParams.get('id')
    // 拿到表单实例
    const [form] = Form.useForm()
    useEffect(() => {
        // 1.通过id获取数据
        async function getArticleDetail() {
            const res = await getArticleDetailAPI(articleId)
            const data = res.data
            const {cover} = data
            // 2.拿到实例对象 回填表单数据
            form.setFieldsValue({
                ...data,
                type: cover.type
            })
            // 回填图片列表类型
            setOnType(cover.type)
            // 数据结构 {url:url}
            setDownLoad(cover.images.map(item => {
                return {url: item}
            }))
            //     为什么封面类型回填不了 因为数据结构不一样 set方法 => {type:3} 实际上 {cover:{type:3}}

        }

        articleId && getArticleDetail()
        if (!articleId) {
            setOnType(0)
            setDownLoad([])
            FormRef.current.resetFields()
        }
    }, [articleId]);
    return (
        <div>
            <Card
                title={<Breadcrumb
                    items={[
                        {title: <Link to="/"><HomeOutlined/> 首页</Link>},
                        {title: `${articleId ? "编辑" : "创建"}文章`}
                    ]}
                />}
                style={{
                    width: "100%",
                    height: "110vh"
                }}>

                {/*表单组件*/}

                <Form
                    name="wrap"
                    labelCol={{
                        flex: '110px',
                    }}
                    ref={FormRef}
                    labelAlign="center"
                    initialValues={{type: 0}}
                    labelWrap
                    wrapperCol={{
                        flex: 1,
                    }}
                    colon={false}
                    style={{
                        maxWidth: 600,
                    }}
                    className={"form_all"}
                    validateTrigger={"onBlur"}
                    onFinish={onFinish}
                    form={form}>

                    {/*输入框组件*/}
                    <Form.Item
                        label="标题"
                        name="title"
                        rules={[
                            {
                                required: true,
                                message: '标题不能为空',
                            },
                        ]}>
                        <Input placeholder={"请输入文章标题"}/>
                    </Form.Item>
                    {/*SELECT选择表单*/}
                    <Form.Item
                        label="频道"
                        name="channel_id"
                        rules={[
                            {
                                required: true,
                                message: '频道不能为空',
                            },
                        ]}>
                        <Select placeholder={"请选择频道"}>
                            {channelList.map((item) => (<Option key={item.id} value={item.id}>{item.name}</Option>))}
                        </Select>
                    </Form.Item>

                    {/*/!*上传照片*!/*/}
                    <Form.Item
                        label={"封面"}>
                        <Form.Item name={"type"} initialValue={0}>
                            <Radio.Group onChange={onTypeChange}>
                                <Radio value={1}>单图</Radio>
                                <Radio value={3}>三图</Radio>
                                <Radio value={0}>无图</Radio>
                            </Radio.Group>
                        </Form.Item>
                        {/*上传组件*/}
                        {/* 1. listType：决定选择文件框的外观样式
                            2. showUploadList：是否显示上传列表
                            3. action 你要上传的地址
                            4. maxCount 支持的最大上传数量*/}
                        {onType > 0 && (
                            <Upload
                                maxCount={onType}
                                listType={"picture-card"}
                                showUploadList
                                action={"https://geek.itheima.net/v1_0/upload"}
                                name={"image"}
                                fileList={downLoad}
                                onChange={onUploadChange}>
                                <div style={{marginTop: 8, color: "#ccc", fontSize: "12px"}}>
                                    <PlusOutlined/>
                                    <div>
                                        上传图片
                                    </div>
                                </div>
                            </Upload>)}

                    </Form.Item>

                    {/*文本内容编辑*/}
                    <Form.Item
                        label="内容"
                        name="content"
                        rules={[
                            {
                                required: true,
                                message: "文章内容不能为空"
                            },
                        ]}>
                        <ReactQuill
                            theme="snow"
                            className="publish_quill"
                            placeholder="请输入文章内容"/>

                    </Form.Item>

                    {/*提交按钮*/}
                    <Form.Item label=" ">
                        <Button type="primary" htmlType="submit">
                            {articleId ? "更新文章" : "发布文章"}
                        </Button>
                    </Form.Item>
                </Form>

            </Card>

        </div>
    )
}
export default Publish